package com.qf.security1.filters;

import com.alibaba.fastjson.JSON;
import com.qf.security1.domain.R;
import com.qf.security1.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    public LoginFilter(AuthenticationManager authenticationManager) {
        setAuthenticationManager(authenticationManager);
    }

    //登录成功的回调
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");

        //生成jwt，发送给前端 (jwt中要包含用户信息和权限信息，不允许包含敏感的信息，比如密码)
        User user = (User) authResult.getPrincipal();
        String username = user.getUsername();
        Collection<GrantedAuthority> authorities = user.getAuthorities();

        //将Collection<GrantedAuthority>类型的集合转成String类型的集合
        List<String> roles = new ArrayList<>();
        if (authorities != null){
            roles = authorities
                    .stream() // 将集合对象转成stream流对象
                    .map(authority-> authority.getAuthority()) //将GrantedAuthority类型的流对象，转成String类型的流
                    .collect(Collectors.toList()); //将流对象转成集合
        }

        //自定义载荷数据
        Map map = new HashMap();
        map.put("username",username);
        map.put("roles",roles);

        //生成jwt
        String token = JwtUtils.createToken(map, username);

        //告诉前端，登录成功
        R r = R.success(token);
        String jsonStr = JSON.toJSONString(r);
        response.getWriter().write(jsonStr);
    }

    //登录失败的回调
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");

        //告诉前端，登录失败
        R r = R.error("用户名或密码错误");
        String jsonStr = JSON.toJSONString(r);
        response.getWriter().write(jsonStr);
    }
}
